<?php

declare(strict_types=1);

namespace owns\logger;

use app\model\system\LoggerOperModel;
use app\model\system\MenuApiModel;
use app\model\system\MenuModel;

class OperLogger
{
    protected $record;
    /**
     * 角色权限验证
     * @param Request $request
     */
    public function permissionVerify($request)
    {
        $baseUrl = $request->baseUrl();
        $method = $request->method();

        $api = MenuApiModel::where('api_method', $method)
            ->where('code', str_replace('/', ':', $baseUrl))
            ->find();
        if ($api) {
            if (!MenuApiModel::where('menu_id', $api->menu_id)->find()) {
                tips('无操作权限');
            }
            // 记录操作信息
            if ($api->is_record) {
                $param = $request->param();
                $this->record = [
                    'username' => $request->auth->username,
                    'method' => $method,
                    'router' => $baseUrl,
                    'service_name' => $api->menu_id,
                    'ip' => $request->ip(),
                    'ip_location' => '',
                    'request_data' => is_array($param) ? json_encode($param) : '',
                ];
                return $this;
            }
        }
        return;
    }

    /**
     * 写入日志
     * @param Response $response
     */
    public function write($response): void
    {
        $this->record['response_code'] = $response->getCode();
        $this->record['response_data'] = $response->getContent();
        // 业务模块
        $service = MenuModel::alias('c')
            ->field('c.title ct,p.title pt')
            ->leftJoin('o_system_menu p', 'p.id = c.parent_id')
            ->where('c.id', $this->record['service_name'])
            ->find();
        $this->record['service_name'] = '【' . $service->pt . '】' . $service->ct;
        $this->record['created_at'] = date('Y-m-d H:i:s');
        $this->record['time_stamp'] = time();
        LoggerOperModel::insert($this->record);
    }
}
